// pages/music/music.js
const {Data} = require("../../utils/data");
Page({
  data: {
  },
  onLoad: async function (options) {
    var module = await import("../../utils/http");
    //获取当前城市
    var position = await module.GetPosition.getLocal();
    var {latitude,longitude} = position;
    var countryRes = await module.GetPosition.getCountry(latitude,longitude);
    var {city} = countryRes.data.result.address_component;
    city = city.slice(0,2);
    this.setData({city,currentCity:city,storageCity:city});
    //得到所有页面http请求的结果
    var bannerRes = await module.MusicHttp.getBanner();
    var hotRes = await module.MusicHttp.getHotMusic();
    var newestRes = await module.MusicHttp.getNewest();
    var djRes = await module.MusicHttp.getDjProgram();
    var hot = this.handleData(hotRes.data.playlists).slice(0,3);
    var dj = this.handleDjData(djRes.data.result).slice(0,3);
    this.setData({
      banners:bannerRes.data.banners,
      hot,
      newest:newestRes.data.albums.slice(0,3),
      dj
    });
  },
  onShow(){
    var currentCity = this.data.city;
    var storageCity = wx.getStorageSync('city')
    if(currentCity != storageCity && storageCity){
      this.sure(currentCity,storageCity)
    }
  },
  sure(currentCity,storageCity){
    wx.showModal({
      cancelColor: '#000000',
      cancelText: '取消',
      confirmColor: '#3CC51F',
      confirmText: '确定',
      content: '当前城市不是您所在的城市，是否切换为所在城市？',
      showCancel: true,
      title: '切换城市',
      success: (result) => this.changeCity(result,currentCity,storageCity),
    })
  },
  changeCity(result,currentCity,storageCity){
    if(result.confirm){
      this.setData({currentCity})
      wx.setStorageSync('city', currentCity)
    }else{
      this.setData({currentCity:storageCity})
    }
  },
  navToSearch(){
    wx.navigateTo({
      url: '/pages/musicSearch/musicSearch',
    })
  },
  handleData(arr){
    var res = [];
    arr.forEach(item=>{
      var{id,name,coverImgUrl,playCount} = item;
      playCount = Data.HandlePlayCount(playCount);
      res.push({id,name,picUrl:coverImgUrl,playCount});
    })
    return res;
  },
  handleDjData(arr){
    arr.forEach(item=>{
      item.program.listenerCount = Data.HandlePlayCount(item.program.listenerCount)
    })
    return arr
  },
  toHot(event){
    var urltype = event.currentTarget.dataset.urltype;
    wx.navigateTo({
      url: `/pages/more/more?urltype=${urltype}`,
    })
  },
  toNewest(event){
    var urltype = event.currentTarget.dataset.urltype;
    wx.navigateTo({
      url: `/pages/more/more?urltype=${urltype}`,
    })
  },
  toDj(event){
    var urltype = event.currentTarget.dataset.urltype;
    wx.navigateTo({
      url: `/pages/more/more?urltype=${urltype}`,
    })
  },
  toAlbum(event){
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/album/album?id=${id}`,
    })
  },
  toCity(){
    wx.navigateTo({
      url: '/pages/city/city',
    })
  }
})